# -*- coding: utf-8 -*-
"""webcrawler.py 百度图片搜索并批量下载
"""
from urllib.request import urlopen, urlretrieve
from urllib.parse import quote
import os
import re
url = "https://image.baidu.com/search/flip?tn=baiduimage&word="
keyword = "高清动漫"


def main():
    if not os.path.exists("img"):
        os.mkdir("img")
    path = os.path.abspath("img")
    try:
        html = urlopen(url + quote(keyword)).read().decode()
        links = re.findall(r'"objURL":"(.+?)"', html)
        for i in links:
            urlretrieve(i, os.path.join(path, i.split("/")[-1]))  # 原文件名保存
    except Exception as e:
        print(repr(e))


if __name__ == "__main__":
    main()
